package ru.nosport.matrixaria.modules.remote;

import org.apache.commons.configuration.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.InetSocketAddress;

import ru.nosport.matrixaria.modules.common.AppServerProcess;

/**
 * User: vfabr
 * Date: 11.10.2006
 * Time: 12:47:25
 */
public class RemoteModule implements AppServerProcess {
	private InetSocketAddress isa;
	private String remoteInstanceName;

	/**
	 * Constructor for the stub object containing information needed to
	 * connect to another core and execute remote object's method.
	 *
	 * @param _conf Configuration, containing remote instance name, IP and port of remote core
	 * @throws IllegalArgumentException
	 */
	public RemoteModule(Configuration _conf) throws IllegalArgumentException {
		this.remoteInstanceName = _conf.getString("remoteInstanceName");
		this.setInetSocketAddress(_conf.getString("ip"), _conf.getInt("port", 1099));
	}

	/**
	 * Sets IP and port for remote core with validation
	 *
	 * @param _ip String with standard IP record or server name
	 * @param _port Socket port
	 * @throws IllegalArgumentException
	 */
	private void setInetSocketAddress(String _ip, int _port) throws IllegalArgumentException {
		try {
			this.isa = new InetSocketAddress(InetAddress.getByName(_ip), _port);
		} catch (IllegalArgumentException _ex) {
			String mess = _ex.getMessage() + ". Remote instance name " + this.remoteInstanceName;
			throw new IllegalArgumentException(mess);
		} catch (UnknownHostException _ex) {
			String mess = "Illegal ip value " + _ip + ". Remote instance name " + this.remoteInstanceName;
			throw new IllegalArgumentException(mess);
		}
	}

	/**
	 * @return Socket address for remote system.
	 */
	public InetSocketAddress getAddress() {
		return this.isa;
	}

	/**
	 * @return Instance name in remote system.
	 */
	public String getRemoteInstanceName() {
		return this.remoteInstanceName;
	}

	public boolean moduleStart() {
		return true;
	}

	public boolean moduleStop() {
		return false;
	}

	public boolean isModuleRunning() {
		return false;
	}

	public String moduleStat() {
		return null;
	}
}
